package com.atguigu.linkedlist;

/**
 * @author shkstart
 * @create 2021-08-09 12:49
 */
public class josepfu {
    public static void main(String[] args) {
        //测试
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        //加入五个小孩
        circleSingleLinkedList.add(25);
//        circleSingleLinkedList.showBoy();
        circleSingleLinkedList.countBody(1,2,25);
    }
}
//创建一个环形的单向链表
class CircleSingleLinkedList{
    private Body first=null;
    //添加节点
    public void add(int nums){
        if (nums<1){
            System.out.println("nums的数不正确！");
            return;
        }
        Body curBody=null;
        for (int i=1;i<=nums;i++){
            Body body = new Body(i);
            if (i==1){
                first=body;
                first.setNext(first);
                curBody=body;
                }else {
                curBody.setNext(body);
                body.setNext(first);
                curBody=body;

            }

        }

    }
    //显示链表
    public void showBoy(){
        if (first==null){
            System.out.println("链表为空！");
            return;
        }
        Body curBoy=first;
        while (true){
            System.out.println("小孩的编号:"+curBoy.getNo());
            if (curBoy.getNext()==first){
                break;
            }
          curBoy=curBoy.getNext();
        }
    }
    //根据用户的输入，计算出小孩出圈的顺序
    public void countBody(int startNo,int countNum,int nums){
        //进行判断
        if (startNo<1||countNum>nums||first==null){
            System.out.println("输入参数有误，请重新输入");
            return;
        }
        //使得helper定位到链表的最后一节点
        Body helper=first;
        while (true){
            if (helper.getNext()==first){
                break;
            }
            helper=helper.getNext();
        }
        //使得first与helper定位到startNO规定的节点
        for (int i=0;i<startNo-1;i++){
            first=first.getNext();
            helper=helper.getNext();
        }
        //实现数据的出圈
        while (true){
            if (helper==first){
                break;
            }
            for (int i=0;i<countNum-1;i++){
                first=first.getNext();
                helper=helper.getNext();
            }
            System.out.println("小孩"+first.getNo()+"出圈");
            //删除出圈小孩
            first=first.getNext();
            helper.setNext(first);

        }
        System.out.println("最后留在圈中的小孩编号为"+first.getNo());

    }
}
//创建一个body类，当作一个节点
class Body{
    private int no;
    private Body next;

    public Body(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Body getNext() {
        return next;
    }

    public void setNext(Body next) {
        this.next = next;
    }
}
